#include <Arduino.h>
#include "Arduino_GFX_Library.h"
#include "CST816T.h"

#define I2C_SDA 16
#define I2C_SCL 15
#define RST_N_PIN 17
#define INT_N_PIN 47

CST816T cst816t(I2C_SDA, I2C_SCL, RST_N_PIN, INT_N_PIN);
/*******************************************************************************
 * End of CST816T setting
 ******************************************************************************/

/* More dev device declaration: https://github.com/moononournation/Arduino_GFX/wiki/Dev-Device-Declaration */
#if defined(DISPLAY_DEV_KIT)
Arduino_GFX *gfx = create_default_Arduino_GFX();
#else /* !defined(DISPLAY_DEV_KIT) */

/* ESP32-S3 various dev board  : CS: 40, DC: 41, RST: 42, BL: 48, SCK: 36, MOSI: 35, MISO: nil  */
/* More data bus class: https://github.com/moononournation/Arduino_GFX/wiki/Data-Bus-Class */
Arduino_DataBus *bus = create_default_Arduino_DataBus();

// Arduino_GFX *gfx = new Arduino_ST7735(bus, 42 /* RST */, 0 /* rotation */, false /* IPS */,128 /* width */, 128 /* height */,0 /* col offset 1 */, 0 /* row offset 1 */);
Arduino_GFX *gfx = new Arduino_ST7789(bus, 17 /* RST */, 0 /* rotation */, true /* IPS */, 240 /* width */, 280 /* height */, 0 /* col offset 1 */, 20 /* row offset 1 */, 0 /* col offset 2 */, 20 /* row offset 2 */);

#endif /* !defined(DISPLAY_DEV_KIT) */
/*******************************************************************************
 * End of Arduino_GFX setting
 ******************************************************************************/
TouchInfos tp;
int count = 0;

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(115200);
  cst816t.begin(mode_motion, true);

#ifdef GFX_EXTRA_PRE_INIT
  GFX_EXTRA_PRE_INIT();
#endif
  // Init Display
  if (!gfx->begin())
  {
    Serial.println("gfx->begin() failed!");
  }
  gfx->fillScreen(GREEN);

#ifdef GFX_BL
  pinMode(GFX_BL, OUTPUT);
  digitalWrite(GFX_BL, HIGH);
#endif

  gfx->setCursor(100, 5);
  gfx->setTextColor(RED);
  gfx->setTextSize(2);
  gfx->println("Hello World!");

  Serial.println("hello world");
  Serial.println(cst816t.chip_id, HEX);
  delay(2000); // 2 seconds
}

uint8_t yp = 10, cnt = 0;
void loop()
{
  // put your main code here, to run repeatedly:
  count++;
  tp = cst816t.GetTouchInfo();

  if (tp.touching)
  {
    Serial.printf("CST816T %d (%d, %4d, %4d)\n", count, tp.touching, tp.x, tp.y);
    if (cnt++ > 3)
    {
      cnt = 0;
      gfx->fillScreen(GREEN);
    }
    gfx->setTextColor(RED, GREEN);
    gfx->setTextSize(2);
    gfx->setCursor(20, 200 + 20 * cnt);

    gfx->printf("CST816T(%3d,%3d)\n", tp.x, tp.y);
  }

  gfx->setCursor(random(gfx->width()), 20 + random(120));
  gfx->setTextColor(random(0xffff), random(0xffff));
  gfx->setTextSize(random(6) /* x scale */, random(6) /* y scale */, random(2) /* pixel_margin */);
  gfx->println("Hello World!");
  delay(50);
}
